package com.itheima.netmarket.impl.view.manager;

import java.util.LinkedList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.RelativeLayout;

import com.itheima.netmarket.formwork.view.manager.UIManager;
import com.itheima.netmarket.impl.view.MainView;
import comitheima.netmarket.R;

/**
 * 
 * @author 武嘉豪
 * 
 */
public class UIManagerImpl implements UIManager {
	private static UIManager uiManager = new UIManagerImpl();
	private Activity activity;
	private LinkedList<MainView> ViewTask = new LinkedList<MainView>();
	private RelativeLayout layout;
	private MainView target;
	private MainView lastView = null;

	private UIManagerImpl() {

	}

	/**
	 * 
	 * @return UIManager的实例
	 */
	public static UIManager getInstance() {
		return uiManager;
	}

	public void init(Activity activity) {
		this.activity = activity;
		layout = (RelativeLayout) activity.findViewById(R.id.testlayout);
	}

	@Override
	public void changeView(Class<? extends MainView> T) {
		try {
			target = T.getConstructor(Context.class).newInstance(getActivity());
			if (lastView == null || (lastView.getClass() != target.getClass())) {
				target.onCreate();
				ViewTask.addFirst(target);
				layout.removeAllViews();
				layout.addView(target.getmView());
				lastView = target;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void changeViewWithBundle(Class<? extends MainView> T, Bundle bundle) {
		try {
			target = T.getConstructor(Context.class).newInstance(getActivity());
			if (lastView == null || (lastView.getClass() != target.getClass())) {
				target.onCreate();
				ViewTask.addFirst(target);
				layout.removeAllViews();
				target.dowithBundle(bundle);
				layout.addView(target.getmView());
				lastView = target;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Activity getActivity() {
		return this.activity;
	}

	@Override
	public MainView getCurrentView() {
		return target;
	}

	@Override
	public MainView getLastView() {
		return ViewTask.get(ViewTask.size() - 1);
	}

	@Override
	public void pressBack() {
		if (ViewTask.size() > 1) {
			ViewTask.removeFirst();
			changeView(ViewTask.getFirst().getClass());
			System.out.println(ViewTask.size());
		} else {
			System.out.println(ViewTask.size());
		}
	}
}
